const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const { User, Friendship } = require('../models/User');
const { Op } = require('sequelize');

// 获取好友列表
router.get('/', auth, async (req, res) => {
    try {
        const user = await User.findByPk(req.user.id);
        const friends = await user.getFriends();
        res.json(friends);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

// 搜索用户
router.get('/search/:account', auth, async (req, res) => {
    try {
        const users = await User.findAll({
            where: {
                account: {
                    [Op.like]: `%${req.params.account}%`
                },
                id: {
                    [Op.ne]: req.user.id
                }
            },
            attributes: ['id', 'account']
        });
        res.json(users);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

// 发送好友请求
router.post('/request/:userId', auth, async (req, res) => {
    try {
        const user = await User.findByPk(req.params.userId);
        if (!user) {
            return res.status(404).json({ msg: '用户不存在' });
        }

        // 检查是否已经是好友
        const existingFriendship = await Friendship.findOne({
            where: {
                [Op.or]: [
                    { userId: req.user.id, friendId: user.id },
                    { userId: user.id, friendId: req.user.id }
                ],
                status: 'accepted'
            }
        });

        if (existingFriendship) {
            return res.status(400).json({ msg: '已经是好友了' });
        }

        // 检查是否已经发送过请求
        const existingRequest = await Friendship.findOne({
            where: {
                userId: req.user.id,
                friendId: user.id,
                status: 'pending'
            }
        });

        if (existingRequest) {
            return res.status(400).json({ msg: '已经发送过好友请求' });
        }

        // 创建好友请求
        await Friendship.create({
            userId: req.user.id,
            friendId: user.id,
            status: 'pending'
        });

        res.json({ msg: '好友请求已发送' });
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

// 处理好友请求
router.put('/request/:requestId', auth, async (req, res) => {
    try {
        const { action } = req.body; // 'accept' 或 'reject'
        const friendship = await Friendship.findOne({
            where: {
                id: req.params.requestId,
                friendId: req.user.id,
                status: 'pending'
            }
        });

        if (!friendship) {
            return res.status(404).json({ msg: '请求不存在' });
        }

        if (action === 'accept') {
            await friendship.update({ status: 'accepted' });
            // 创建双向好友关系
            await Friendship.create({
                userId: req.user.id,
                friendId: friendship.userId,
                status: 'accepted'
            });
            res.json({ msg: '已添加好友' });
        } else {
            await friendship.update({ status: 'rejected' });
            res.json({ msg: '已拒绝请求' });
        }
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

// 获取好友请求列表
router.get('/requests', auth, async (req, res) => {
    try {
        const requests = await Friendship.findAll({
            where: {
                friendId: req.user.id,
                status: 'pending'
            },
            include: [{
                model: User,
                as: 'sender',
                attributes: ['id', 'account']
            }]
        });
        res.json(requests);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('服务器错误');
    }
});

module.exports = router; 